<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class KCrypt extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'kcrypt:d {ciphertext} {ts} {pos} ';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '解密前后端交互密文';

    /**
     * Execute the console command.
     */
    public function handle(): void
    {
        $sData = $this->argument('ciphertext');
        $sKey = $this->argument('ts');
        $pos = (int)$this->argument('pos');

        $text = self::decrypt($sData, $sKey);
        var_dump($text, true) . PHP_EOL;
    }

    public static function encrypt($sData, $sKey)
    {
        $sResult = '';
        for ($i = 0; $i < strlen($sData); $i++) {
            $sChar    = substr($sData, $i, 1);
            $sKeyChar = substr($sKey, ($i % strlen($sKey)) - 1, 1);
            $sChar    = chr(ord($sChar) + ord($sKeyChar));
            $sResult .= $sChar;
        }
        return self::encodeBase64($sResult);
    }

    public static function decrypt($sData, $sKey)
    {
        $sResult = '';
        $sData   = self::decodeBase64($sData);
        for ($i = 0; $i < strlen($sData); $i++) {
            $sChar    = substr($sData, $i, 1);
            $sKeyChar = substr($sKey, ($i % strlen($sKey)) - 1, 1);
            $sChar    = chr(ord($sChar) - ord($sKeyChar));
            $sResult .= $sChar;
        }
        return $sResult;
    }

    public static function encodeBase64($sData)
    {
        $sBase64 = base64_encode($sData);
        return strtr($sBase64, '+/', '-_');
    }

    public static function decodeBase64($sData)
    {
        $sBase64 = strtr($sData, '-_', '+/');
        return base64_decode($sBase64);
    }
}
